<template>
  <div>
    <n-form>
      <n-card
          title="图片放大"
          style="width: 600px"
          :bordered="false"
      >
        <n-grid x-gap="10">
          <n-grid-item :span="24">
            <n-h6>
              {{ `原图信息(高度:` + props.paintConfig.defaultHeight * (props.paintConfig.defaultEnableHr ? 2 : 1) + `      宽度:` + props.paintConfig.defaultWidth * (props.paintConfig.defaultEnableHr ? 2 : 1) + `    高清重绘:` + (props.paintConfig.defaultEnableHr ? '开启' : '未开启') + ` )` }}
            </n-h6>
          </n-grid-item>
          <n-grid-item :span="12">
            <n-form-item label="缩放倍数">
              <n-input-number v-model:value="upscaleForm.upscaleResize" :min="2" :max="4"></n-input-number>
            </n-form-item>
          </n-grid-item>
          <n-grid-item :span="6">
            <n-form-item label="缩放后高度">
              <n-input-number
                  style="width: 100%"
                  readonly
                  :value="props.paintConfig.defaultHeight * (props.paintConfig.defaultEnableHr? 2:1) * upscaleForm.upscaleResize">
              </n-input-number>
            </n-form-item>

          </n-grid-item>
          <n-grid-item :span="6">
            <n-form-item label="缩放后宽度">
              <n-input-number
                  style="width: 100%"
                  readonly
                  :value="props.paintConfig.defaultWidth * (props.paintConfig.defaultEnableHr? 2:1) * upscaleForm.upscaleResize">
              </n-input-number>
            </n-form-item>
          </n-grid-item>
          <n-grid-item :span="12">
            <n-form-item label="放大引擎">
              <n-select
                  style="width: 100%"
                  :options="upscaleEngineTypeOptions"
                  v-model:value="upscaleForm.upscaleEngine"
                  @update:value="upscaleEngineChange"
              ></n-select>
            </n-form-item>
          </n-grid-item>
          <n-grid-item :span="12">
            <n-form-item label="放大算法">
              <n-select
                  :loading="upscaleForm.getScalerModelLading"
                  style="width: 100%"
                  :options="upscalers"
                  v-model:value="upscaleForm.upscalerModel"
              ></n-select>
            </n-form-item>
          </n-grid-item>
          <n-grid-item :span="12">
            <n-form-item :show-label="false">
              <n-checkbox v-model:checked="upscaleForm.skipFlag">跳过已完成</n-checkbox>
            </n-form-item>
          </n-grid-item>
        </n-grid>
        <Schdule :schedule="schedule"></Schdule>
        <template #footer>
          <n-space justify="space-between">
            <n-button
                type="primary"
                @click="batchUpscale"
                v-if="!schedule.scheduleOperatingFlag"
            >放大</n-button>

            <n-button
                type="warning"
                v-if="!schedule.scheduleOperatingFlag"
                @click="closeFunction">取消
            </n-button>

          </n-space>
          <n-button
              type="error"
              style="margin-top:5px;"
              @click="shutDownTask"
              block
              v-if="schedule.scheduleOperatingFlag && schedule.currentTaskNum < schedule.taskStatus.totalNum">终止任务
          </n-button>

          <n-button
            type="info"
            block
            v-if="schedule.scheduleOperatingFlag && schedule.currentTaskNum == schedule.taskStatus.totalNum"
            @click="closeFunction">
            关闭
          </n-button>
        </template>
      </n-card>
    </n-form>
  </div>
</template>

<style scoped>

</style>
<script setup lang="ts">
import {NButton, NSelect, NSpace} from "naive-ui";
import {sdControllerApi} from "@/api/sd/sdController.api";
import Schdule from '@/components/creator/function/schdule.vue'

const {upscaleEngineTypeOptions, realESRGANModelTypeOptions} = creatorDict()

import {reactive, ref} from "vue";
import {creatorDict} from "@/dictionary/creatorDict";
import {storyBoardController} from "@/api/controller/story/storyBoard.api";

const props = defineProps({
  paintConfig: {
    type: Object,
    required: true
  },
  resourceId: {
    type: String,
    required: true
  },
  upsacleList: {
    type: Array,
    required: true
  },
  closeFunction: {
    type: Function,
    required: true
  },
  storyId: {
    type: String,
    required: true
  }
})

const upscaleForm = reactive({
  upscaleResize: 2,
  upscaleEngine: 'realesrgan',
  upscalerModel: 'realesr-animevideov3',
  getScalerModelLading: false,
  skipFlag: true
})


const schedule = reactive({
  scheduleOperatingFlag: false,
  currentTaskNum: 0,
  stopLoop: false,
  taskStatus: {
    successNum: 0,
    failNum: 0,
    totalNum: 0
  }
})

const upscalers = ref(realESRGANModelTypeOptions.value)

const upscaleEngineChange = (value: string) => {
  upscaleForm.upscaleEngine = value
  upscaleForm.upscalerModel = ''
  if (upscaleForm.upscaleEngine === 'sd') {
    getUpscaler()
  } else {
    // 获取当前的算法
    upscalers.value = realESRGANModelTypeOptions.value
    upscaleForm.upscalerModel = upscalers.value[0].value
  }
}

// 获取反推的算法
const getUpscaler = () => {
  upscaleForm.getScalerModelLading = true
  upscalers.value = []
  sdControllerApi.getUpscaler(props.resourceId).then(res => {
    if (res.code === 200) {
      JSON.parse(res.data).forEach((item: any) => {
        upscalers.value.push({
          label: item.name,
          value: item.name
        })
      })
      upscaleForm.upscalerModel = upscalers.value[0].value
    } else {
      window.$message.error("无法获取SD的放大算法,请自行查看SD!")
    }
  }).finally(() => {
    upscaleForm.getScalerModelLading = false
  })
}


//
const batchUpscale = async () => {
  if (upscaleForm.upscalerModel === '') {
    window.$message.warning("请选择放大算法")
    return
  }
  if (upscaleForm.upscalerModel === 'realesrgan-x4plus' && upscaleForm.upscaleResize !== 4) {
    window.$message.warning("realesrgan-x4plus只能放大4倍")
    return
  }
  resetSchedule()
  schedule.taskStatus.totalNum = props.upsacleList.length
  schedule.scheduleOperatingFlag = true
  for (const item of props.upsacleList) {
    if (schedule.stopLoop) {
      break
    }
    schedule.currentTaskNum++
    try {
      const param = {
        scale: upscaleForm.upscaleResize,
        upscaleEngine: upscaleForm.upscaleEngine,
        modelName: upscaleForm.upscalerModel,
        skipFlag: upscaleForm.skipFlag,
        storyBoardId: item.id,
        storyId: props.storyId
      }
      const res = await storyBoardController.upscale(param)
      if (res.code === 200) {
        // 成功
        schedule.taskStatus.successNum++
      } else {
        schedule.taskStatus.failNum++
      }
    } catch (e) {
      schedule.taskStatus.failNum++
    }
  }
}


const shutDownTask = () => {
  window.$dialog.warning({
    title: "提示",
    content: "是否停止任务?",
    positiveText: "确认",
    negativeText: "取消",
    onPositiveClick: () => {
      schedule.stopLoop = true
      schedule.scheduleOperatingFlag = false
    }
  })
}

const resetSchedule = () => {
  schedule.currentTaskNum = 0
  schedule.taskStatus = {
    successNum: 0,
    failNum: 0,
    totalNum: 0
  }
  schedule.scheduleOperatingFlag = false
  schedule.stopLoop = false
}
</script>
